<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>服务器监控面板</title>
    <script src="./js/chart.js"></script>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
        }

        h1 {
            color: #333;
            text-align: center;
        }

        .card {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            padding: 20px;
            margin-bottom: 20px;
        }

        .stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-item {
            text-align: center;
            padding: 15px;
            background-color: #f9f9f9;
            border-radius: 6px;
        }

        .stat-item h3 {
            color: #666;
            margin-bottom: 10px;
        }

        .stat-item .value {
            font-size: 24px;
            font-weight: bold;
            color: #333;
        }

        .charts {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
            gap: 20px;
        }

        .chart-container {
            height: 300px;
            position: relative;
        }

        .progress-bar {
            height: 20px;
            background-color: #e0e0e0;
            border-radius: 10px;
            overflow: hidden;
            margin-top: 10px;
        }

        .progress {
            height: 100%;
            border-radius: 10px;
            transition: width 0.5s ease;
        }

        .cpu-progress {
            background-color: #4CAF50;
        }

        .memory-progress {
            background-color: #2196F3;
        }

        .disk-progress {
            background-color: #ff9800;
        }

        /* 标签页样式 */
        .tabs {
            display: flex;
            margin-bottom: 20px;
            border-bottom: 1px solid #ddd;
        }

        .tab {
            padding: 10px 20px;
            cursor: pointer;
            border: 1px solid transparent;
            border-bottom: none;
            background-color: #f1f1f1;
        }

        .tab.active {
            background-color: white;
            border-color: #ddd;
            border-top-left-radius: 8px;
            border-top-right-radius: 8px;
            font-weight: bold;
        }

        .tab-content {
            display: none;
        }

        .tab-content.active {
            display: block;
        }

        .font-list {
            max-height: 400px;
            overflow-y: auto;
            border: 1px solid #ddd;
            padding: 10px;
            border-radius: 4px;
        }

        .font-item {
            padding: 5px;
            border-bottom: 1px solid #eee;
        }

        .font-item:last-child {
            border-bottom: none;
        }

        .jvm-info {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 10px;
        }

        .jvm-item {
            padding: 8px;
            background-color: #f9f9f9;
            border-radius: 4px;
        }

        .jvm-item strong {
            display: inline-block;
            width: 120px;
        }

        .zip-form {
            margin-bottom: 20px;
            padding: 15px;
            background-color: #f9f9f9;
            border-radius: 6px;
        }

        .zip-form button {
            padding: 8px 16px;
            background-color: #2196F3;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        .zip-form button:hover {
            background-color: #0b7dda;
        }
    </style>
</head>
<body>
<div class="container">
    <h1>服务器监控面板</h1>

    <!-- 标签页 -->
    <div class="tabs">
        <div class="tab active" data-tab="overview">系统概览</div>
        <div class="tab" data-tab="jvm">JVM信息</div>
        <div class="tab" data-tab="fonts">可用字体</div>
        <div class="tab" data-tab="zip">日志下载</div>
    </div>

    <!-- 系统概览标签页 -->
    <div class="tab-content active" id="overview">
        <div class="card">
            <h2>系统信息</h2>
            <div id="system-info">
                <p>加载系统信息中...</p>
            </div>
        </div>

        <div class="stats">
            <div class="stat-item">
                <h3>CPU使用率</h3>
                <div class="value" id="cpu-usage">--%</div>
                <div class="progress-bar">
                    <div class="progress cpu-progress" id="cpu-bar" style="width: 0%"></div>
                </div>
            </div>
            <div class="stat-item">
                <h3>内存使用率</h3>
                <div class="value" id="memory-usage">--%</div>
                <div class="progress-bar">
                    <div class="progress memory-progress" id="memory-bar" style="width: 0%"></div>
                </div>
            </div>
            <div class="stat-item">
                <h3>磁盘使用率</h3>
                <div class="value" id="disk-usage">--%</div>
                <div class="progress-bar">
                    <div class="progress disk-progress" id="disk-bar" style="width: 0%"></div>
                </div>
            </div>
        </div>

        <div class="charts">
            <div class="card">
                <h3>CPU使用历史</h3>
                <div class="chart-container">
                    <canvas id="cpu-chart"></canvas>
                </div>
            </div>
            <div class="card">
                <h3>内存使用历史</h3>
                <div class="chart-container">
                    <canvas id="memory-chart"></canvas>
                </div>
            </div>
            <div class="card">
                <h3>磁盘使用情况</h3>
                <div class="chart-container">
                    <canvas id="disk-chart"></canvas>
                </div>
            </div>
        </div>
    </div>

    <!-- JVM信息标签页 -->
    <div class="tab-content" id="jvm">
        <div class="card">
            <h2>JVM信息</h2>
            <div id="jvm-info" class="jvm-info">
                <p>加载JVM信息中...</p>
            </div>
        </div>
    </div>

    <!-- 可用字体标签页 -->
    <div class="tab-content" id="fonts">
        <div class="card">
            <h2>系统可用字体</h2>
            <div id="fonts-loading">加载字体信息中...</div>
            <div id="fonts-list" class="font-list" style="display: none;"></div>
        </div>
    </div>

    <!-- 目录打包标签页 -->
    <div class="tab-content" id="zip">
        <div class="card">
            <h2>日志下载</h2>
            <div class="zip-form">
                <button onclick="downloadZip()">下载</button>
                <span id="zip-status"></span>
            </div>

            <div id="zip-info">
                <p>注意：应用程序需要有日志目录的读取权限。</p>
                <p>大型目录可能需要较长时间处理，请耐心等待。</p>
            </div>
        </div>
    </div>
</div>

<script>
    // 标签页切换功能
    document.querySelectorAll('.tab').forEach(tab => {
        tab.addEventListener('click', () => {
            // 移除所有活动状态
            document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
            document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));

            // 添加当前活动状态
            tab.classList.add('active');
            const tabId = tab.getAttribute('data-tab');
            document.getElementById(tabId).classList.add('active');

            // 切换到JVM或字体标签页时加载数据
            if (tabId === 'jvm') {
                fetchJvmInfo();
            } else if (tabId === 'fonts') {
                fetchFonts();
            }
        });
    });

    // 数据存储
    const cpuData = {
        labels: [],
        values: []
    };

    const memoryData = {
        labels: [],
        values: []
    };

    // 图表对象
    let cpuChart, memoryChart, diskChart;

    // 初始化图表
    function initCharts() {
        // CPU图表
        cpuChart = new Chart(document.getElementById('cpu-chart'), {
            type: 'line',
            data: {
                labels: cpuData.labels,
                datasets: [{
                    label: 'CPU使用率 (%)',
                    data: cpuData.values,
                    borderColor: '#4CAF50',
                    backgroundColor: 'rgba(76, 175, 80, 0.1)',
                    fill: true,
                    tension: 0.1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        max: 100,
                        title: {
                            display: true,
                            text: '使用率 (%)'
                        }
                    }
                }
            }
        });

        // 内存图表
        memoryChart = new Chart(document.getElementById('memory-chart'), {
            type: 'line',
            data: {
                labels: memoryData.labels,
                datasets: [{
                    label: '内存使用率 (%)',
                    data: memoryData.values,
                    borderColor: '#2196F3',
                    backgroundColor: 'rgba(33, 150, 243, 0.1)',
                    fill: true,
                    tension: 0.1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        max: 100,
                        title: {
                            display: true,
                            text: '使用率 (%)'
                        }
                    }
                }
            }
        });

        // 磁盘图表
        diskChart = new Chart(document.getElementById('disk-chart'), {
            type: 'doughnut',
            data: {
                labels: ['已使用', '空闲'],
                datasets: [{
                    data: [0, 100],
                    backgroundColor: ['#ff9800', '#e0e0e0']
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom'
                    }
                }
            }
        });
    }

    // 更新系统信息
    function updateSystemInfo(data) {
        document.getElementById('system-info').innerHTML = `
                <p><strong>操作系统:</strong> ${data.os}</p>
                <p><strong>CPU:</strong> ${data.cpu.name}（物理核心: ${data.cpu.physicalCores}，逻辑核心: ${data.cpu.logicalCores}）</p>
                <p><strong>内存:</strong> 总计 ${data.memory.totalFormatted}，已使用 ${data.memory.usedFormatted}</p>
                <p><strong>磁盘:</strong> 总计 ${data.disk.totalFormatted}，已使用 ${data.disk.usedFormatted}</p>
                <p><strong>运行时间:</strong> ${data.uptime}</p>
            `;
    }

    // 更新统计信息
    function updateStats(data) {
        // 更新CPU信息
        const cpuUsage = data.cpu.usage.toFixed(1);
        document.getElementById('cpu-usage').textContent = `${cpuUsage}%`;
        document.getElementById('cpu-bar').style.width = `${cpuUsage}%`;

        // 更新内存信息
        const memoryUsage = data.memory.usedPercent.toFixed(1);
        document.getElementById('memory-usage').textContent = `${memoryUsage}%`;
        document.getElementById('memory-bar').style.width = `${memoryUsage}%`;

        // 更新磁盘信息
        const diskUsage = data.disk.usedPercent.toFixed(1);
        document.getElementById('disk-usage').textContent = `${diskUsage}%`;
        document.getElementById('disk-bar').style.width = `${diskUsage}%`;

        // 更新图表数据
        const now = new Date().toLocaleTimeString();

        // 限制数据点数量
        if (cpuData.values.length > 30) {
            cpuData.values.shift();
            cpuData.labels.shift();
        }
        if (memoryData.values.length > 30) {
            memoryData.values.shift();
            memoryData.labels.shift();
        }

        cpuData.values.push(parseFloat(cpuUsage));
        cpuData.labels.push(now);
        cpuChart.data.labels = cpuData.labels;
        cpuChart.data.datasets[0].data = cpuData.values;
        cpuChart.update();

        memoryData.values.push(parseFloat(memoryUsage));
        memoryData.labels.push(now);
        memoryChart.data.labels = memoryData.labels;
        memoryChart.data.datasets[0].data = memoryData.values;
        memoryChart.update();

        // 更新磁盘图表
        diskChart.data.datasets[0].data = [diskUsage, 100 - parseFloat(diskUsage)];
        diskChart.update();
    }

    // 获取系统信息
    function fetchSystemInfo() {
        fetch('/api/system/overview')
            .then(response => response.json())
            .then(data => {
                updateSystemInfo(data);
                updateStats(data);
            })
            .catch(error => console.error('获取系统信息失败:', error));
    }

    // 获取JVM信息
    function fetchJvmInfo() {
        fetch('/api/system/jvm')
            .then(response => response.json())
            .then(data => {
                let html = '';
                for (const [key, value] of Object.entries(data)) {
                    html += `<div class="jvm-item"><strong>${key}:</strong> ${value}</div>`;
                }
                document.getElementById('jvm-info').innerHTML = html;
            })
            .catch(error => {
                document.getElementById('jvm-info').innerHTML = `<p>加载JVM信息失败: ${error.message}</p>`;
            });
    }

    // 获取字体列表
    function fetchFonts() {
        const loadingDiv = document.getElementById('fonts-loading');
        const listDiv = document.getElementById('fonts-list');

        loadingDiv.style.display = 'block';
        listDiv.style.display = 'none';

        fetch('/api/system/fonts')
            .then(response => response.json())
            .then(data => {
                let html = '';
                data.forEach(font => {
                    html += `<div class="font-item">${font}</div>`;
                });
                listDiv.innerHTML = html;

                loadingDiv.style.display = 'none';
                listDiv.style.display = 'block';
            })
            .catch(error => {
                loadingDiv.innerHTML = `<p>加载字体信息失败: ${error.message}</p>`;
            });
    }

    // 下载ZIP文件（固定目录）
    function downloadZip() {
        const statusSpan = document.getElementById('zip-status');

        statusSpan.textContent = '处理中...';
        statusSpan.style.color = 'orange';

        const url = `/api/system/zip`;  // 无参数请求

        // 创建隐藏链接触发下载
        const link = document.createElement('a');
        link.href = url;

        // 先通过fetch检查是否成功
        fetch(url)
            .then(response => {
                if (!response.ok) {
                    throw new Error('打包失败，请检查目录权限');
                }
                statusSpan.textContent = '下载中...';
                statusSpan.style.color = 'green';
                link.click();
                setTimeout(() => {
                    statusSpan.textContent = '';
                }, 3000);
            })
            .catch(error => {
                statusSpan.textContent = '错误: ' + error.message;
                statusSpan.style.color = 'red';
            });
    }

    // 初始化
    window.onload = function () {
        initCharts();
        fetchSystemInfo();

        // 每5秒更新一次系统概览数据
        setInterval(fetchSystemInfo, 5000);
    };
</script>
</body>
</html>